package org.ytor.core.exception;

import jakarta.servlet.http.HttpServletResponse;
import org.ytor.common.enums.RespCode;
import org.ytor.common.exception.BaseException;
import org.ytor.common.exception.DownloadException;
import org.ytor.common.model.R;
import org.ytor.core.util.RespUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BaseException.class)
    public R<?> baseExceptionHandler(BaseException e) {
        log.error(e.getMessage(), e);
        logging(e);
        return R.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(DownloadException.class)
    public R<?> baseExceptionHandler(DownloadException e) {
        HttpServletResponse resp = RespUtil.getResp();
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);

        log.error(e.getMessage(), e);
        logging(e);

        return R.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R<?> exceptionHandler(Exception e) {
        HttpServletResponse resp = RespUtil.getResp();
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);

        log.error(e.getMessage(), e);
        logging(e);

        return R.error(RespCode.FAIL.code, e.getClass().getName() + ":" + e.getMessage());
    }

    /**
     * 记录异常日志
     */
    private void logging(Exception e) {
        //TODO 记录异常日志
    }
}
